
#include "Main.h"          // Main header

#include "FridgeScript.h"  // My header

#include "FridgeScript_API.h"

#define LUA_SUCCESS 0

// --------------------- Lua implementation ----------------------------------

lua_State* FridgeScript::s_pxLua = 0;
char FridgeScript::s_szScriptOutput[ uFS_SCRIPT_OUTPUT_BUFFER ];

void FridgeScript::Initialise()
{
	FridgeLog("Fridgescript init\n");

	s_pxLua = lua_open();
	luaL_openlibs( s_pxLua );

	FridgeScript_API::RegisterFunctions( s_pxLua );

	memset( s_szScriptOutput, 0, sizeof( char ) * uFS_SCRIPT_OUTPUT_BUFFER );
}

void FridgeScript::Shutdown()
{
	lua_close( s_pxLua );
}

void FridgeScript::Execute( const char* szScript, const char* szFunc, const char* szID )
{
	AppendToScriptOutput( "~ Calling " );
	AppendToScriptOutput( szFunc );
	AppendToScriptOutput( "\r\n" );

	int iResult = 0;
	iResult = luaL_loadbuffer( s_pxLua, szScript, strlen( szScript ), szID );
	if( iResult == LUA_SUCCESS )
	{
		iResult = lua_pcall( s_pxLua, 0, 0, 0 );
		if( iResult == LUA_SUCCESS )
		{
			lua_getfield( s_pxLua, LUA_GLOBALSINDEX, szFunc );
			iResult = lua_pcall( s_pxLua, 0, 0, 0 );
		}
	}
	if( iResult != LUA_SUCCESS ) 
	{
		AppendToScriptOutput( "! " );
		AppendToScriptOutput( lua_tostring( s_pxLua, -1 ) );
		AppendToScriptOutput( "\r\n" );
		lua_pop( s_pxLua, 1 );
	}
	else
	{
		AppendToScriptOutput( "~ " );
		AppendToScriptOutput( szFunc );
		AppendToScriptOutput( " completed\r\n" );
	}

	FridgeScript_API::CleanUp();
}

void FridgeScript::AppendToScriptOutput( const char* szText )
{
	// TODO: Make safer
	strcat( s_szScriptOutput, szText );
}

// eof
